<?php
require_once($_SERVER['DOCUMENT_ROOT'].'../system/config.php');

if (!isset($_REQUEST['username']) || $_REQUEST['username'] == '') {
	header('HTTP/1.1 400 Bad Request');
	die('Missing required field: username');
}
else {
	$username = $_REQUEST['username'];
}
if (!isset($_REQUEST['password']) || $_REQUEST['password'] == '') {
	header('HTTP/1.1 400 Bad Request');
	die('Missing required field: password');
}
else {
	$password = md5($_REQUEST['password']);
}

// open database
// fail on database errors
try {
	$db = new PDO("sqlite:".$DATABASE);
} catch (PDOException $e) {
	header('HTTP/1.1 500 Internal Server Error');
	die('Sorry, there is a problem with the database');
}


$query = "SELECT username, password FROM user WHERE username = :username";
$stmt = $db->prepare($query);
$stmt->bindParam(':username', $username);
$stmt->execute();

$result = $stmt->fetch(PDO::FETCH_ASSOC);
if ($result === false) {
	header('HTTP/1.1 400 Bad Request');
	die('username/password mismatch');
}
if ($result['password'] != $password) {
	header('HTTP/1.1 400 Bad Request');
	die('username/password mismatch');
}

header('HTTP/1.1 200 OK');
echo 'welcome';
?>
